#include "LedManager.h"

const quint8 LedManager::COLOR_ENABLE_MASK = 0x80;
const quint32 LedManager::SPI_DEVICE = 0;
const quint32 LedManager::NUM_COLORS = 3;

LedManager::LedManager() :
   Plugin(),
   theSpi(SPI_DEVICE),
   theNumberLeds(0),
   theStripData()
{
   // Blank intentionally
}

Plugin* LedManager::getPlugin()
{
   return this;
}

void LedManager::initializeLedStrip()
{
   quint32 numLatchBytes = ((theNumberLeds + 63) / 64) * NUM_COLORS;
   theStripData = QByteArray(numLatchBytes, 0x00);

   if(theSpi.openPort() && theSpi.transfer(&theStripData))
   {
      qDebug() << "Succesfully initialized LED strip";
   }
   else
   {
      qCritical() << "Failed to initialize LED strip";
   }

   theStripData = QByteArray(theNumberLeds * NUM_COLORS, COLOR_ENABLE_MASK);
}

void LedManager::slotStartService()
{
   QVariant value;
   emit signalGetConfigValue(KEY_NUM_LEDS, value);
   theNumberLeds = value.toUInt();

   initializeLedStrip();
}

void LedManager::slotStopService()
{
   // Blank intentionally
}

void LedManager::slotConfigUpdate(const QString &key,
                                  QVariant &value)
{
   if(key == KEY_NUM_LEDS)
   {
      theNumberLeds = value.toUInt();
      initializeLedStrip();
   }
}

void LedManager::slotEventNotification(Event event)
{
   Q_UNUSED(event)
   // Blank intentionally
}

void LedManager::slotSetColor(quint32 led,
                              QColor color)
{
   if(led < theNumberLeds)
   {
      quint32 greenIndex = led * NUM_COLORS;
      quint32 redIndex = (led * NUM_COLORS) + 1;
      quint32 blueIndex = (led * NUM_COLORS) + 2;

      theStripData.insert(greenIndex, (color.green() | COLOR_ENABLE_MASK));
      theStripData.insert(redIndex, (color.red() | COLOR_ENABLE_MASK));
      theStripData.insert(blueIndex, (color.blue() | COLOR_ENABLE_MASK));

      theSpi.transfer(&theStripData);
   }
}

Q_EXPORT_PLUGIN(LedManager)
